import com.codezen.helper.Worker;

import flash.events.Event;

import logic.AnimeDataLoader;

import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.utils.ObjectUtil;

import utils.anime.AniEpisode;
import utils.anime.AniSerial;

private var an:AnimeDataLoader;

// data providers
[Bindable]
private var lastAniEpisodes:ArrayCollection;
[Bindable]
private var animeList:ArrayCollection;

// current episode
public var currentAniEpisode:AniEpisode;

// current anime series
public var currentAniSeries:AniSerial;

private function onAniAuthLoad(evt:Event):void{
	// remove event listener
	an.removeEventListener(Event.INIT, onAniAuthLoad);
	
	// init
	lastAniEpisodes = new ArrayCollection();
	
	// get last eps
	var item:AniEpisode;
	for each(item in an.lastEpisodes){
		lastAniEpisodes.addItem(item);
	}
	
	// check new eps from DB
	dbAniLoadNewEpisodes();
	
	// clean
	//item = null;
	
	// change state
	//currentState = "Main";
	
	// get series
	an.addEventListener(Event.COMPLETE, onAniDataLoad);
	an.requestData();
}

private function onAniDataLoad(evt:Event):void{
	// remove event listener
	an.removeEventListener(Event.COMPLETE, onAniDataLoad);
	
	// init
	animeList = new ArrayCollection();
	
	// set series
	var item:AniSerial;
	for each(item in an.seriesList){
		animeList.addItem(item);
	}
	
	// create sort by names
	var sort:Sort = new Sort();
	sort.fields = [new SortField("title")];
	
	// sort
	animeList.sort = sort;
	animeList.refresh();
	
	// load series from DB
	dbAniLoadSeries();
	
	// clean
	//item = null;
	//sort = null;
	
	// force GC
	//startGCCycle();
}

private function loadAnime(id:String):void{
	an.addEventListener(Event.COMPLETE, onAnimeLoad);
	an.loadSeries(id);
}

private function onAnimeLoad(e:Event):void{
	an.removeEventListener(Event.COMPLETE, onAnimeLoad);
	
	// init
	episodesList = new ArrayCollection();
	
	// get eps
	var item:AniEpisode;
	for each(item in an.episodesList){
		episodesList.addItem(item);
	}
	
	// clean
	item = null;
	
	// set seasons
	breakAniSeasons();
}

private function breakAniSeasons():void{
	seasonsList = new ArrayCollection();
	
	var tmp:Array = [];
	var item:AniEpisode;
	for each(item in episodesList){
		if(tmp.lastIndexOf(item.season) < 0){
			tmp.push(item.season);
			seasonsList.addItem({label:"Сезон "+item.season,season:item.season});
		}
	}
	
	// clean
	item = null;
	tmp = null;
	
	// force GC
	startGCCycle();
	
	// set index
	seasons_combobox.selectedIndex = 0;
	filterAniSeasons(null);
}